package com.andatsoft.laisim.activity.setting;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.activity.BaseActivity;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.dialog.SkinChooserDialog;
import com.andatsoft.laisim.entity.SkinItem;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.ToastMessage;
import com.andatsoft.laisim.view.WPProgressBar;

public class SkinSettingActivity extends BaseActivity {

	private LinearLayout mLayoutSkinScan;
	private LinearLayout mLayoutSkinSelect;
	private LinearLayout mLayoutSkinSelectOnline;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_skin);
		initViews();
		setupListeners();
	}

	private void initViews() {
		((TextView) findViewById(R.id.tv_setting_skin_name))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_1)
						+ ": " + ThemeManager.getSelectedSkin().getSkinName());
		((TextView) findViewById(R.id.tv_setting_skin_author))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_2)
						+ ": " + ThemeManager.getSelectedSkin().getAuthorName());
		((TextView) findViewById(R.id.tv_setting_skin_info))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_3)
						+ ": " + ThemeManager.getSelectedSkin().getAuthorInfo());
		mLayoutSkinScan = (LinearLayout) findViewById(R.id.layout_setting_skin_scan);
		mLayoutSkinSelect = (LinearLayout) findViewById(R.id.layout_setting_skin_select_skin);
		mLayoutSkinSelectOnline = (LinearLayout) findViewById(R.id.layout_setting_skin_select_skin_online);

	}

	private void setupListeners() {
		mLayoutSkinScan.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					new SkinScanner().execute();
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

		mLayoutSkinSelect.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					startActivity(new Intent(SkinSettingActivity.this,
							SkinChooserDialog.class));
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

		mLayoutSkinSelectOnline.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					try {
						startActivity(new Intent(Intent.ACTION_VIEW, Uri
								.parse("market://search?q=laisim&c=apps")));
					} catch (android.content.ActivityNotFoundException anfe) {
						startActivity(new Intent(
								Intent.ACTION_VIEW,
								Uri.parse("http://play.google.com/store/apps/search?q=laisim&c=apps")));
					}
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

	}

	class SkinScanner extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPreExecute() {
			mLayoutSkinScan.setEnabled(false);
			((WPProgressBar) findViewById(R.id.wp_progress_skin_scan))
					.setVisibility(View.VISIBLE);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			int skinFound = 0;
			String path = Environment.getExternalStorageDirectory()
					+ "/Laisim/Skin/";
			File f = new File(path);
			if (!f.exists())
				f.mkdirs();
			File[] fList = f.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					String name = pathname.getAbsolutePath();
					if (name.substring(name.lastIndexOf(".") - 1).contains(
							"skin"))
						return true;
					return false;
				}
			});
			if (fList != null && fList.length > 0) {
				DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
				for (int i = 0; i < fList.length; i++) {
					SkinItem item = extractSkinName(fList[i].getAbsolutePath());

					// add theme to db
					item.id = (int) db.addSkinInfo(item.name, item.author,
							item.address, false);
					if (item.id != -1)
						skinFound++;
				}
			}
			return skinFound;
		}

		private SkinItem extractSkinName(String input) {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			Document doc;
			SkinItem item = new SkinItem();
			item.address = input;
			item.isSelected = 0;
			try {
				ZipInputStream zis = new ZipInputStream(new FileInputStream(
						input));

				ZipEntry ze = zis.getNextEntry();
				while (ze != null) {
					String fileName = ze.getName();
					if (fileName.equals("skinExtraInfo.si")) {
						byte[] buffer = new byte[1024];
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						int len;
						while ((len = zis.read(buffer)) > 0) {
							out.write(buffer, 0, len);
						}
						out.flush();
						InputStream is = new ByteArrayInputStream(
								out.toByteArray());
						DocumentBuilder docBuilder = docFactory
								.newDocumentBuilder();
						doc = docBuilder.parse(is);

						doc.getDocumentElement().normalize();

						// get all node with the tag name is LaisimTheme
						NodeList nodeStuList = doc
								.getElementsByTagName("LaisimSkin");

						// we only have 1 node, so the first node is wanted node
						Node node = nodeStuList.item(0);

						if (node.getNodeType() == Node.ELEMENT_NODE) {
							Element e = (Element) node;

							String text = e.getElementsByTagName("AuthorName")
									.item(0).getTextContent();
							item.author = text;

							text = e.getElementsByTagName("SkinName").item(0)
									.getTextContent();
							item.name = text;
						}
						is.close();
						out.close();
						zis.closeEntry();
						zis.close();
					}
					ze = zis.getNextEntry();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return item;
		}

		@Override
		protected void onPostExecute(Integer result) {
			mLayoutSkinScan.setEnabled(true);
			((WPProgressBar) findViewById(R.id.wp_progress_skin_scan))
					.setVisibility(View.GONE);
			if (result == null)
				result = 0;
			if (result < 2) {
				new ToastMessage(getApplicationContext())
						.showShortMessage(result + " "
								+ getString(R.string.toast_number_skin_found));
			} else {
				new ToastMessage(getApplicationContext())
						.showShortMessage(result
								+ " "
								+ getString(R.string.toast_number_skin_found_plural));
			}
		}
	}
}
